import { useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import { Row, Col, MessagePlugin, Pagination } from 'tdesign-react'
import Header from '@/apps/bilibili/components/Header'
import SortNavigate from '@/apps/bilibili/components/SortNavigate'
import VideoItem from '@/apps/bilibili/components/VideoItem'
import fs from 'fs'
import { ApiRequest, apis } from '@/service'

import styles from './index.module.less'


const {
  home: {
    getEntryVideo,
  },
} = apis.BilibiliService

const HomePage = (props: any) => {
  const navigate = useNavigate()
  const [videoSort, setVideoSort] = useState<any>({ label: '动画', value: '1' })
  const [sortList, setSortList] = useState<any[]>([])
  const [hotList, setHotList] = useState<any[]>([])

  const OPTIONS = [
    { label: '动画', value: '1' },
    { label: '音乐', value: '2' },
    { label: '游戏', value: '3' },
    { label: '科技', value: '4' },
    { label: '生活', value: '5' },
  ]
  useEffect(() => {
    // getEntryVideoFnc()
    // setSortList(_sortList)
    // setHotList(_hotList.list)
    getEntryVideoFnc('precious')
  }, [])

  /**
   * 使用本地接口获取b站数据
   * @param lng
   * @returns
   */
  const getEntryVideoFnc = async (localPath: string) => {
    // TODO: 获取入站必刷视频
    let localRes = await fetch(`/bllocal/${localPath}.json`).then((res: any) => {
      return res && res.json()
    }).then((data: any) => {
      return data
    }).catch((err: any) => {
      console.error(err)
      return {
        code: -1,
        note: '获取本地文件失败'
      }
    })
    // 此处得到的res 与接口的res 一模一样
    console.log('res1', localRes)
    setSortList(localRes.data?.list)
    setHotList(localRes.data?.list)
    // 如果没有本地文件，则请求bilibili数据并提示保存
    if (localRes.code == -1) {
      ApiRequest({ api: getEntryVideo }).then((res: any) => {
        setHotList(res.data.list)
        setSortList(res.data.list)
        console.log(res)
        let content = JSON.stringify(res)
        console.log(content)
        fs.writeFile(`/public/bllocal/${localPath}.json`, content, (err: any) => {
          if (err) {
            MessagePlugin.error(err)
          } else {
            MessagePlugin.success('文件已写入缓存中')
          }
        })
        // function copyToClipboard(textToCopy: string) {
        //   // navigator clipboard 需要https等安全上下文
        //   if (false) {
        //       // navigator clipboard 向剪贴板写文本
        //       return navigator.clipboard.writeText(textToCopy);
        //   } else {
        //       // 创建text area
        //       let textArea = document.createElement("textarea");
        //       textArea.value = textToCopy;
        //       // 使text area不在viewport，同时设置不可见
        //       textArea.style.position = "absolute";
        //       textArea.style.opacity = "0";
        //       textArea.style.left = "-999999px";
        //       textArea.style.top = "-999999px";
        //       document.body.appendChild(textArea);
        //       textArea.focus();
        //       textArea.select();
        //       return new Promise((res, rej) => {
        //           // 执行复制命令并移除文本框
        //           document.execCommand('copy') ? res('1') : rej();
        //           textArea.remove();
        //       });
        //   }
        // }
        // copyToClipboard(content)
        // return result
        // navigator.clipboard.writeText(JSON.stringify(res))
        //   .then(() => {
        //     // console.log('Text copied to clipboard...')
        //     MessagePlugin.info('数据已复制到剪切板')
        //   })
        //   .catch(err => {
        //     console.log('Something went wrong', err);
        //     MessagePlugin.error('复制数据失败请手动复制')
        //   })
        // } else {
        //   MessagePlugin.error({
        //     content: note,
        //     placement: 'top-right',
        //     duration: 2000
        //   })
        // }
      })
    }
  }

  const onSortChange = (value: { label: string, value: string }) => {
    //TODO切换视频分类
    setVideoSort(value)
  }



  const onKeywordChange = (searchValue: string) => {
    console.log('searchValue',searchValue)
    navigate('/aio/bilibili/search', {
      state: {
        keyword: searchValue,
      }
    })
  }

  const onVideoClick = (item: any) => {
    //TODO跳转播放视频
    navigate('/aio/bilibili/play', {
      state: {
        aid: item.aid,
      }
    })
  }

  const onAuthorClick = (item: any) => {
    //TODO跳转到作者主页
    navigate('/aio/bilibili/user', {
      state: {
        mid: item.owner.mid
      }
    })
  }


  return <div className={styles.homePage}>
    <div className={styles.headerWrapper}>
      <Header className={styles.header} onChange={onKeywordChange} />

    </div>

    <div className={styles.contentWrapper}>
      <div className={styles.sort}>
        <SortNavigate onSortChange={onSortChange} options={OPTIONS} />
        <Row gutter={[16, 16]} className={styles.sortVideoList}>
          {sortList?.map((item: any, index: any) => (
            <Col span={4} key={index}>
              <VideoItem key={index} videoItem={item} direction={'vertical'} onAuthorClick={onAuthorClick} onVideoClick={onVideoClick}/>
            </Col>
          ))}
        </Row>
        <Pagination
          defaultPageSize={10}
          size="medium"
          theme="default"
          total={sortList.length}
        />
      </div>
      <div className={styles.rank}>
        <div className={styles.rankTitle}>入站必刷</div>
        {hotList?.map((item: any, index: any) => (
          <VideoItem key={index} videoItem={item} direction={'horizontal'} className={styles.rankItem} onAuthorClick={onAuthorClick} onVideoClick={onVideoClick}/>
        ))}
      </div>
    </div>

  </div>
}

export default HomePage
